package com.mo.lib.utils

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.content.ContentUris
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.hardware.Camera
import android.hardware.Camera.CameraInfo
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import androidx.core.content.FileProvider
import com.dylanc.longan.application
import com.mo.lib.constans.MEDIA_CHOOSE_PIC
import com.mo.lib.constans.MEDIA_TAKE_PIC
import com.mo.lib.constans.MEDIA_TAKE_VIDEO
import com.xuexiang.xutil.data.DateUtils
import java.io.File
import java.io.IOException

/**
 * @ author：mo
 * @ data：2017/6/13：11:03
 * @ 功能：相机工具类
 */
    /**检测相机是否存在 、摄像头硬件是否可用 */
    fun isExistCamera()= application.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)
    /**判断是否有后置摄像头 */
    fun hasBackFacingCamera()= checkCameraFacing(CameraInfo.CAMERA_FACING_BACK)
    /**判断是否有前置摄像头 */
    fun hasFrontFacingCamera()= checkCameraFacing(CameraInfo.CAMERA_FACING_FRONT)

/**
 * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
 */
 fun createImageUri(): Uri? {
    val status = Environment.getExternalStorageState() // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
    return if (status == Environment.MEDIA_MOUNTED) {
        application.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ContentValues())
    } else {
        application.contentResolver.insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, ContentValues())
    }
}

/**
 * 开启拍照 跳系统相机并返回图片的uri
 *
 * @param mActivity
 * @return
 */
fun actionPhoneTake(mActivity: Activity): Uri? {
    val imageUri: Uri
    val outImage = File(application.externalCacheDir, DateUtils.getNowMills().toString() + "_phone.img")
    try {
        if (outImage.exists()) {
            outImage.delete()
        }
        outImage.createNewFile()
    } catch (e: IOException) {
        e.printStackTrace()
    } //        if (isAndroidQ) {
    //            // 适配android 10
    //            imageUri = createImageUri();
    //        } else
    imageUri = if (Build.VERSION.SDK_INT >= 24) {
        FileProvider.getUriForFile(mActivity, application.packageName + ".fileprovider", outImage)
    } else {
        Uri.fromFile(outImage)
    }
    val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
    mActivity.startActivityForResult(intent, MEDIA_TAKE_PIC)
    return imageUri
}
fun actionPhoneChoose(mActivity: Activity) {
    val intent = Intent("android.intent.action.GET_CONTENT")
    intent.type = "image/*"
    mActivity.startActivityForResult(intent, MEDIA_CHOOSE_PIC)
}

fun actionMediaTakeVideo(mActivity: Activity): Uri? {
    val videoUri: Uri
    val outVideo = File(application.externalCacheDir, DateUtils.getNowMills().toString() + "_video.mp4")
    try {
        if (outVideo.exists()) {
            outVideo.delete()
        }
        outVideo.createNewFile()
    } catch (e: IOException) {
        e.printStackTrace()
    }
    videoUri = if (Build.VERSION.SDK_INT >= 24) {
        FileProvider.getUriForFile(mActivity, application.packageName + ".fileprovider", outVideo) //            LogUtil.i(AppInfoUtil.getAppInfo().getPackageName() + ".fileprovider");
    } else {
        Uri.fromFile(outVideo)
    }

    //        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    //        intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
    //        mActivity.startActivityForResult(intent, KConstans.MEDIA_TAKE_PIC);
    val intent = Intent()
    intent.action = "android.media.action.VIDEO_CAPTURE"
    intent.addCategory("android.intent.category.DEFAULT")
    intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri)
    mActivity.startActivityForResult(intent, MEDIA_TAKE_VIDEO)
    return videoUri
}

/**
 * 处理选择图片后的结果
 *
 * @param data
 * @return
 */
fun handlerImageChooseResult(data: Intent): String? {
    return if (Build.VERSION.SDK_INT >= 19) { //            4.4(19)版本以上从相册选取图片后处理返回图片
        handlerImageAfter19(data)
    } else { //            4.4(19)版本以下从相册选取图片后处理返回图片
        getImagePath(data.data, null)
    }
}

/**
 * 4.4(19)版本以上从相册选取图片后处理返回图片
 *
 * @param data
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
fun handlerImageAfter19(data: Intent): String? {
    var imagePath: String? = null
    val uri = data.data //如果是document类型的uri，则通过document id来处理
    if (DocumentsContract.isDocumentUri(application, uri)) {
        val docId = DocumentsContract.getDocumentId(uri)
        if ("com.android.providers.media.documents" == uri!!.authority) {
            val id = docId.split(":".toRegex()).toTypedArray()[1]
            val selection = MediaStore.Images.Media._ID + "=" + id
            imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection)
        } else if ("com.android.providers.downloads.documents" == uri.authority) {
            val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(docId))
            imagePath = getImagePath(contentUri, null)
        } //如果是content类型的URI，则使用普通方式处理
    } else if ("content".equals(uri!!.scheme, ignoreCase = true)) {
        imagePath = getImagePath(uri, null) //如果是file类型的URI，则直接获取图片路径
    } else if ("file".equals(uri.scheme, ignoreCase = true)) {
        imagePath = uri.path
    }
    return imagePath
}

/**
 * 通过Uri和selection 获取真实的图片路径
 *
 * @param uri
 * @param selection
 * @return
 */
@SuppressLint("Range")
fun getImagePath(uri: Uri?, selection: String?): String? {
    var path: String? = null
    val cursor = application.contentResolver.query(uri!!, null, selection, null, null)
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
        }
        cursor.close()
    }
    return path
}

/** 判断是否有某朝向的摄像头    facing 摄像头朝向, 前置或后置*/
     fun checkCameraFacing(facing: Int): Boolean {
        val cameraCount = Camera.getNumberOfCameras()
        val info = CameraInfo()
        for (i in 0 until cameraCount) {
            Camera.getCameraInfo(i, info)
            if (facing == info.facing) {
                return true
            }
        }
        return false
    }